1
use std::{
2
    fs,
3
    os::unix::fs::FileTypeExt,
4
    path::{Path, PathBuf},
5
    sync::{Arc, atomic::AtomicU64},
6
    time::Duration,
7
};
8

            
9
use anyhow::{Context, anyhow};
10
use clap_verbosity_flag::{InfoLevel, Verbosity};
11
use nix::{
12
    libc::{EXIT_SUCCESS, exit},
13
    unistd::{AccessFlags, access},
14
};
15
use sqlx::mysql::MySqlPoolOptions;
16
use std::os::unix::net::UnixStream as StdUnixStream;
17
use tokio::net::UnixStream as TokioUnixStream;
18
use tracing_subscriber::prelude::*;
19

            
20
use crate::{
21
    core::{
22
        common::{DEFAULT_CONFIG_PATH, DEFAULT_SOCKET_PATH, UnixUser, executing_in_suid_sgid_mode},
23
        protocol::request_validation::GroupDenylist,
24
    },
25
    server::{
26
        authorization::read_and_parse_group_denylist,
27
        config::{MysqlConfig, ServerConfig},
28
        landlock::landlock_restrict_server,
29
        session_handler::{self, SessionId},
30
    },
31
};
32

            
33
/// Determine whether we will make a connection to an external server
34
/// or start an internal server with elevated privileges.
35
///
36
/// If neither is feasible, an error is returned.
37
fn will_connect_to_external_server(
38
    server_socket_path: Option<&PathBuf>,
39
    // This parameter is only used in suid-sgid-mode
40
    #[allow(unused_variables)] config_path: Option<&PathBuf>,
41
) -> anyhow::Result<bool> {
42
    if server_socket_path.is_some() {
43
        return Ok(true);
44
    }
45

            
46
    #[cfg(feature = "suid-sgid-mode")]
47
    if config_path.is_some() {
48
        return Ok(false);
49
    }
50

            
51
    if fs::metadata(DEFAULT_SOCKET_PATH).is_ok() {
52
        return Ok(true);
53
    }
54

            
55
    #[cfg(feature = "suid-sgid-mode")]
56
    if fs::metadata(DEFAULT_CONFIG_PATH).is_ok() {
57
        return Ok(false);
58
    }
59

            
60
    #[cfg(feature = "suid-sgid-mode")]
61
    anyhow::bail!("No socket path or config path provided, and no default socket or config found");
62

            
63
    #[cfg(not(feature = "suid-sgid-mode"))]
64
    anyhow::bail!("No socket path provided, and no default socket found");
65
}
66

            
67
/// This function is used to bootstrap the connection to the server.
68
/// This can happen in two ways:
69
///
70
/// 1. If a socket path is provided, or exists in the default location,
71
///    the function will connect to the socket and authenticate with the
72
///    server to ensure that the server knows the uid of the client.
73
///
74
/// 2. If a config path is provided, or exists in the default location,
75
///    and the config is readable, the function will assume it is either
76
///    setuid or setgid, and will fork a child process to run the server
77
///    with the provided config. The server will exit silently by itself
78
///    when it is done, and this function will only return for the client
79
///    with the socket for the server.
80
///
81
/// If neither of these options are available, the function will fail.
82
///
83
/// Note that this function is also responsible for setting up logging,
84
/// because in the case of an internal server, we need to drop privileges
85
/// before we can initialize logging.
86
///
87
/// **WARNING:** This function may be run with elevated privileges.
88
pub fn bootstrap_server_connection_and_drop_privileges(
89
    server_socket_path: Option<PathBuf>,
90
    config: Option<PathBuf>,
91
    verbose: Verbosity<InfoLevel>,
92
) -> anyhow::Result<StdUnixStream> {
93
    if will_connect_to_external_server(server_socket_path.as_ref(), config.as_ref())? {
94
        assert!(
95
            !executing_in_suid_sgid_mode()?,
96
            "The executable should not be SUID or SGID when connecting to an external server"
97
        );
98

            
99
        init_stderr_tracing_subscriber(verbose)?;
100

            
101
        connect_to_external_server(server_socket_path)
102
    } else if cfg!(feature = "suid-sgid-mode") {
103
        // NOTE: We need to be really careful with the code up until this point,
104
        //       as we might be running with elevated privileges.
105
        let server_connection = bootstrap_internal_server_and_drop_privs(config)?;
106

            
107
        init_stderr_tracing_subscriber(verbose)?;
108

            
109
        Ok(server_connection)
110
    } else {
111
        anyhow::bail!("SUID/SGID support is not enabled, cannot start internal server");
112
    }
113
}
114

            
115
fn init_stderr_tracing_subscriber(verbose: Verbosity<InfoLevel>) -> anyhow::Result<()> {
116
    let env_filter = tracing_subscriber::EnvFilter::builder()
117
        .with_default_directive(verbose.tracing_level_filter().into())
118
        .from_env_lossy();
119

            
120
    let subscriber = tracing_subscriber::Registry::default()
121
        .with(env_filter)
122
        .with(
123
            tracing_subscriber::fmt::layer()
124
                .with_line_number(cfg!(debug_assertions))
125
                .with_target(cfg!(debug_assertions))
126
                .with_thread_ids(false)
127
                .with_thread_names(false),
128
        );
129

            
130
    tracing::subscriber::set_global_default(subscriber)
131
        .context("Failed to set global default tracing subscriber")
132
}
133

            
134
fn socket_path_is_ok(path: &Path) -> anyhow::Result<()> {
135
    fs::metadata(path)
136
        .context(format!("Failed to get metadata for {:?}", path))
137
        .and_then(|meta| {
138
            if !meta.file_type().is_socket() {
139
                anyhow::bail!("{:?} is not a unix socket", path);
140
            }
141

            
142
            access(path, AccessFlags::R_OK | AccessFlags::W_OK)
143
                .with_context(|| format!("Socket at {:?} is not readable/writable", path))?;
144

            
145
            Ok(())
146
        })
147
}
148

            
149
fn connect_to_external_server(
150
    server_socket_path: Option<PathBuf>,
151
) -> anyhow::Result<StdUnixStream> {
152
    if let Some(socket_path) = server_socket_path {
153
        tracing::trace!("Checking socket at {:?}", socket_path);
154
        socket_path_is_ok(&socket_path)?;
155

            
156
        tracing::debug!("Connecting to socket at {:?}", socket_path);
157
        return match StdUnixStream::connect(socket_path) {
158
            Ok(socket) => Ok(socket),
159
            Err(e) => match e.kind() {
160
                std::io::ErrorKind::NotFound => Err(anyhow::anyhow!("Socket not found")),
161
                std::io::ErrorKind::PermissionDenied => Err(anyhow::anyhow!("Permission denied")),
162
                _ => Err(anyhow::anyhow!("Failed to connect to socket: {e}")),
163
            },
164
        };
165
    }
166

            
167
    if fs::metadata(DEFAULT_SOCKET_PATH).is_ok() {
168
        tracing::trace!("Checking socket at {:?}", DEFAULT_SOCKET_PATH);
169
        socket_path_is_ok(Path::new(DEFAULT_SOCKET_PATH))?;
170

            
171
        tracing::debug!("Connecting to default socket at {:?}", DEFAULT_SOCKET_PATH);
172
        return match StdUnixStream::connect(DEFAULT_SOCKET_PATH) {
173
            Ok(socket) => Ok(socket),
174
            Err(e) => match e.kind() {
175
                std::io::ErrorKind::NotFound => Err(anyhow::anyhow!("Socket not found")),
176
                std::io::ErrorKind::PermissionDenied => Err(anyhow::anyhow!("Permission denied")),
177
                _ => Err(anyhow::anyhow!("Failed to connect to socket: {e}")),
178
            },
179
        };
180
    }
181

            
182
    anyhow::bail!(
183
        "No socket path provided, and no socket found found at default location {DEFAULT_SOCKET_PATH}"
184
    );
185
}
186

            
187
// TODO: this function is security critical, it should be integration tested
188
//       in isolation.
189
/// Drop privileges to the real user and group of the process.
190
/// If the process is not running with elevated privileges, this function
191
/// is a no-op.
192
pub fn drop_privs() -> anyhow::Result<()> {
193
    tracing::debug!("Dropping privileges");
194
    let real_uid = nix::unistd::getuid();
195
    let real_gid = nix::unistd::getgid();
196

            
197
    nix::unistd::setuid(real_uid).context("Failed to drop privileges")?;
198
    nix::unistd::setgid(real_gid).context("Failed to drop privileges")?;
199

            
200
    debug_assert_eq!(nix::unistd::getuid(), real_uid);
201
    debug_assert_eq!(nix::unistd::getgid(), real_gid);
202

            
203
    tracing::debug!("Privileges dropped successfully");
204
    Ok(())
205
}
206

            
207
/// Bootstrap an internal server by forking a child process to run the server, giving it
208
/// the other half of a Unix socket pair to communicate with the client process.
209
fn bootstrap_internal_server_and_drop_privs(
210
    config_path: Option<PathBuf>,
211
) -> anyhow::Result<StdUnixStream> {
212
    if let Some(config_path) = config_path {
213
        if !executing_in_suid_sgid_mode()? {
214
            anyhow::bail!("Executable is not SUID/SGID - refusing to start internal sever");
215
        }
216

            
217
        // ensure config exists and is readable
218
        if fs::metadata(&config_path).is_err() {
219
            return Err(anyhow::anyhow!("Config file not found or not readable"));
220
        }
221

            
222
        tracing::debug!("Starting server with config at {:?}", config_path);
223
        let socket = invoke_server_with_config(&config_path)?;
224
        drop_privs()?;
225
        return Ok(socket);
226
    }
227

            
228
    let config_path = PathBuf::from(DEFAULT_CONFIG_PATH);
229
    if fs::metadata(&config_path).is_ok() {
230
        if !executing_in_suid_sgid_mode()? {
231
            anyhow::bail!("Executable is not SUID/SGID - refusing to start internal sever");
232
        }
233
        tracing::debug!("Starting server with default config at {:?}", config_path);
234
        let socket = invoke_server_with_config(&config_path)?;
235
        drop_privs()?;
236
        return Ok(socket);
237
    }
238

            
239
    anyhow::bail!("No config path provided, and no default config found");
240
}
241

            
242
// TODO: we should somehow ensure that the forked process is killed on completion,
243
//       just in case the client does not behave properly.
244
/// Fork a child process to run the server with the provided config.
245
/// The server will exit silently by itself when it is done, and this function
246
/// will only return for the client with the socket for the server.
247
fn invoke_server_with_config(config_path: &Path) -> anyhow::Result<StdUnixStream> {
248
    let (server_socket, client_socket) = StdUnixStream::pair()?;
249
    let unix_user = UnixUser::from_uid(nix::unistd::getuid().as_raw())?;
250

            
251
    match (unsafe { nix::unistd::fork() }).context("Failed to fork")? {
252
        nix::unistd::ForkResult::Parent { .. } => Ok(client_socket),
253
        nix::unistd::ForkResult::Child => {
254
            landlock_restrict_server(Some(config_path))
255
                .context("Failed to apply Landlock restrictions to the server process")?;
256

            
257
            match run_forked_server(config_path, server_socket, &unix_user) {
258
                Err(e) => Err(e),
259
                Ok(()) => unreachable!(),
260
            }
261
        }
262
    }
263
}
264

            
265
/// Construct a `MySQL` connection pool that consists of exactly one connection.
266
///
267
/// This is used for the internal server in SUID/SGID mode, where the server session
268
/// only ever will get a single client.
269
async fn construct_single_connection_mysql_pool(
270
    config: &MysqlConfig,
271
) -> anyhow::Result<sqlx::MySqlPool> {
272
    let mysql_config = config.as_mysql_connect_options()?;
273

            
274
    let pool_opts = MySqlPoolOptions::new()
275
        .max_connections(1)
276
        .min_connections(1);
277

            
278
    config.log_connection_notice();
279

            
280
    let pool = match tokio::time::timeout(
281
        Duration::from_secs(config.timeout),
282
        pool_opts.connect_with(mysql_config),
283
    )
284
    .await
285
    {
286
        Ok(connection) => connection.context("Failed to connect to the database"),
287
        Err(_) => Err(anyhow!("Timed out after {} seconds", config.timeout))
288
            .context("Failed to connect to the database"),
289
    }?;
290

            
291
    Ok(pool)
292
}
293

            
294
/// Run a single server session in the forked process.
295
///
296
/// This function will not return, but will exit the process with a success code.
297
/// The function assumes that it's caller has already forked the process.
298
fn run_forked_server(
299
    config_path: &Path,
300
    server_socket: StdUnixStream,
301
    unix_user: &UnixUser,
302
) -> anyhow::Result<()> {
303
    let config = ServerConfig::read_config_from_path(config_path)
304
        .context("Failed to read server config in forked process")?;
305

            
306
    let group_denylist = if let Some(denylist_path) = &config.authorization.group_denylist_file {
307
        read_and_parse_group_denylist(denylist_path)
308
            .context("Failed to read and parse group denylist")?
309
    } else {
310
        GroupDenylist::new()
311
    };
312

            
313
    let result: anyhow::Result<()> = tokio::runtime::Builder::new_current_thread()
314
        .enable_all()
315
        .build()
316
        .context("Failed to start Tokio runtime")?
317
        .block_on(async {
318
            let socket = TokioUnixStream::from_std(server_socket)?;
319
            let db_pool = construct_single_connection_mysql_pool(&config.mysql).await?;
320
            let db_is_mariadb = {
321
                let mut conn = db_pool.acquire().await?;
322
                let version_row: String = sqlx::query_scalar("SELECT VERSION()")
323
                    .fetch_one(&mut *conn)
324
                    .await
325
                    .context("Failed to query MySQL version")?;
326
                version_row.to_lowercase().contains("mariadb")
327
            };
328

            
329
            let session_id = SessionId::new(0);
330
            let db_pool = Arc::new(db_pool);
331
            session_handler::session_handler_with_unix_user(
332
                socket,
333
                session_id,
334
                unix_user,
335
                db_pool,
336
                db_is_mariadb,
337
                &group_denylist,
338
                Arc::new(AtomicU64::new(0)),
339
            )
340
            .await?;
341
            Ok(())
342
        });
343

            
344
    result?;
345

            
346
    unsafe {
347
        exit(EXIT_SUCCESS);
348
    }
349
}