aboutsummaryrefslogtreecommitdiffstats
path: root/letmeind/src/protocol.rs
blob: 76df5af452efab7dd06d5c3e967890e7a595fc61 (plain)
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
// -*- coding: utf-8 -*-
//
// Copyright (C) 2024 Michael Büsch <m@bues.ch>
//
// Licensed under the Apache License version 2.0
// or the MIT license, at your option.
// SPDX-License-Identifier: Apache-2.0 OR MIT

use crate::{
    firewall_client::{FirewallClient, PortType},
    server::ConnectionOps,
};
use anyhow::{self as ah, format_err as err};
use letmein_conf::{Config, ErrorPolicy, Resource};
use letmein_proto::{Message, Operation, ResourceId, UserId};
use std::{net::SocketAddr, path::Path};
use tokio::time::timeout;

/// Protocol authentication state.
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
#[allow(clippy::enum_variant_names)]
enum AuthState {
    /// Not authenticated.
    NotAuth,

    /// Basic (not replay-safe) authentication passed.
    BasicAuth,

    /// Full challenge-response authentication passed.
    ChallengeResponseAuth,
}

/// Implementation of the wire protocol message sequence.
pub struct Protocol<'a, C> {
    conn: C,
    conf: &'a Config,
    rundir: &'a Path,
    user_id: Option<UserId>,
    resource_id: Option<ResourceId>,
    auth_state: AuthState,
}

impl<'a, C: ConnectionOps> Protocol<'a, C> {
    pub fn new(conn: C, conf: &'a Config, rundir: &'a Path) -> Self {
        Self {
            conn,
            conf,
            rundir,
            user_id: None,
            resource_id: None,
            auth_state: AuthState::NotAuth,
        }
    }

    pub fn addr(&self) -> SocketAddr {
        self.conn.addr()
    }

    async fn recv_msg(&mut self, expect_operation: Operation) -> ah::Result<Message> {
        if let Some(msg) = timeout(self.conf.control_timeout(), self.conn.recv_msg())
            .await
            .map_err(|_| err!("RX communication with peer timed out"))??
        {
            if msg.operation() != expect_operation {
                let _ = self.send_go_away().await;
                return Err(err!(
                    "Invalid reply message operation. Expected {:?}, got {:?}",
                    expect_operation,
                    msg.operation()
                ));
            }
            if let Some(user_id) = self.user_id {
                if msg.user() != user_id {
                    let _ = self.send_go_away().await;
                    return Err(err!("Received message user mismatch"));
                }
            }
            if let Some(resource_id) = self.resource_id {
                if msg.resource() != resource_id {
                    let _ = self.send_go_away().await;
                    return Err(err!("Received message resource mismatch"));
                }
            }
            Ok(msg)
        } else {
            Err(err!("Disconnected."))
        }
    }

    async fn send_msg(&mut self, msg: &Message) -> ah::Result<()> {
        timeout(self.conf.control_timeout(), self.conn.send_msg(msg))
            .await
            .map_err(|_| err!("TX communication with peer timed out"))?
    }

    async fn send_go_away(&mut self) -> ah::Result<()> {
        // Check if we are allowed to send the error message.
        match self.conf.control_error_policy() {
            ErrorPolicy::Always => (),
            ErrorPolicy::BasicAuth => {
                if self.auth_state != AuthState::BasicAuth
                    && self.auth_state != AuthState::ChallengeResponseAuth
                {
                    return Ok(());
                }
            }
            ErrorPolicy::FullAuth => {
                if self.auth_state != AuthState::ChallengeResponseAuth {
                    return Ok(());
                }
            }
        }

        // Send the error message.
        self.send_msg(&Message::new(
            Operation::GoAway,
            self.user_id.unwrap_or(u32::MAX.into()),
            self.resource_id.unwrap_or(u32::MAX.into()),
        ))
        .await
    }

    pub async fn run(&mut self) -> ah::Result<()> {
        self.user_id = None;
        self.resource_id = None;
        self.auth_state = AuthState::NotAuth;

        // Receive the initial knock message.
        let knock = self.recv_msg(Operation::Knock).await?;

        let user_id = knock.user();
        self.user_id = Some(user_id);

        let resource_id = knock.resource();
        self.resource_id = Some(resource_id);

        // Get the shared key.
        let Some(key) = self.conf.key(user_id) else {
            let _ = self.send_go_away().await;
            return Err(err!("Unknown user: {user_id}"));
        };

        // Authenticate the received message.
        // This check is not replay-safe. But that's fine.
        if !knock.check_auth_ok_no_challenge(key) {
            let _ = self.send_go_away().await;
            return Err(err!("Knock: Authentication failed"));
        }
        self.auth_state = AuthState::BasicAuth;

        // Get the requested resource from the configuration.
        let Some(resource) = self.conf.resource(resource_id) else {
            let _ = self.send_go_away().await;
            return Err(err!("Unknown resource: {resource_id}"));
        };

        // Check if the authenticating user is allowed to access this resource.
        match resource {
            Resource::Port {
                port,
                tcp: _,
                udp: _,
                users: _,
            } => {
                // Check the mapped user on the resource.
                if !resource.contains_user(user_id) {
                    let _ = self.send_go_away().await;
                    return Err(err!(
                        "Resource {resource_id} not allowed for user {user_id}"
                    ));
                }
                // The control port is never allowed.
                let control_port = self.conf.port();
                if *port == control_port {
                    let _ = self.send_go_away().await;
                    return Err(err!(
                        "Incorrect configuration: The resource {resource_id} uses the \
                         letmein control port {control_port}. That is not allowed."
                    ));
                }
            }
        }

        // Generate and send a challenge.
        let mut challenge = Message::new(Operation::Challenge, user_id, resource_id);
        challenge.generate_challenge();
        self.send_msg(&challenge).await?;

        // Receive the response.
        let response = self.recv_msg(Operation::Response).await?;

        // Authenticate the challenge-response.
        if !response.check_auth_ok(key, challenge) {
            let _ = self.send_go_away().await;
            return Err(err!("Response: Authentication failed"));
        }
        self.auth_state = AuthState::ChallengeResponseAuth;

        // Reconfigure the firewall.
        match resource {
            Resource::Port {
                port,
                tcp,
                udp,
                users: _,
            } => {
                // Port type to open.
                let port_type = match (tcp, udp) {
                    (true, false) => PortType::Tcp,
                    (false, true) => PortType::Udp,
                    (true, true) => PortType::TcpUdp,
                    (false, false) => unreachable!(),
                };

                // Connect to letmeinfwd unix socket.
                let mut fw = match FirewallClient::new(self.rundir).await {
                    Err(e) => {
                        let _ = self.send_go_away().await;
                        return Err(err!("Failed to connect to letmeinfwd: {e}"));
                    }
                    Ok(fw) => fw,
                };

                // Send an open-port request to letmeinfwd.
                assert_eq!(self.auth_state, AuthState::ChallengeResponseAuth);
                if let Err(e) = fw.open_port(self.addr().ip(), port_type, *port).await {
                    let _ = self.send_go_away().await;
                    return Err(err!("letmeinfwd firewall open: {e}"));
                }
            }
        }

        // Send a come-in message.
        let comein = Message::new(Operation::ComeIn, user_id, resource_id);
        self.send_msg(&comein).await?;

        Ok(())
    }
}

// vim: ts=4 sw=4 expandtab
bues.ch cgit interface