signstar_configure_build/lib.rs
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
use std::{
fs::File,
io::Write,
path::{Path, PathBuf},
process::{id, Command, ExitStatus},
str::FromStr,
};
use nethsm_config::{HermeticParallelConfig, SystemUserId, UserMapping};
use nix::unistd::User;
use sysinfo::{Pid, System};
pub mod cli;
pub static ETC_OVERRIDE_CONFIG_FILE: &str = "/etc/signstar/config.toml";
pub static RUN_OVERRIDE_CONFIG_FILE: &str = "/run/signstar/config.toml";
pub static USR_LOCAL_OVERRIDE_CONFIG_FILE: &str = "/usr/local/share/signstar/config.toml";
pub static DEFAULT_CONFIG_FILE: &str = "/usr/share/signstar/config.toml";
pub static SSH_AUTHORIZED_KEY_BASE_DIR: &str = "/etc/ssh";
pub static SSHD_DROPIN_CONFIG_DIR: &str = "/etc/ssh/sshd_config.d";
pub static HOME_BASE_DIR: &str = "/var/lib/signstar/home";
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// A config error
#[error("Configuration issue: {0}")]
Config(#[from] nethsm_config::Error),
/// A [`Command`] exited unsuccessfully
#[error("The command exited with non-zero status code (\"{exit_status}\") and produced the following output on stderr:\n{stderr}")]
CommandNonZero {
exit_status: ExitStatus,
stderr: String,
},
/// A `u32` value can not be converted to `usize` on the current platform
#[error("Unable to convert u32 to usize on this platform.")]
FailedU32ToUsizeConversion,
/// There is no SSH ForceCommand defined for a [`UserMapping`]
#[error("No SSH ForceCommand defined for user mapping (NetHSM users: {nethsm_users:?}, system user: {system_user})")]
NoForceCommandForMapping {
nethsm_users: Vec<String>,
system_user: String,
},
/// No process information could be retrieved from the current PID
#[error("The information on the current process could not be retrieved")]
NoProcess,
/// The application is not run as root
#[error("This application must be run as root!")]
NotRoot,
/// No process information could be retrieved from the current PID
#[error("No user ID could be retrieved for the current process with PID {0}")]
NoUidForProcess(usize),
/// A string could not be converted to a sysinfo::Uid
#[error("The string {0} could not be converted to a \"sysinfo::Uid\"")]
SysUidFromStr(String),
/// Adding a user failed
#[error("Adding user {user} failed:\n{source}")]
UserAdd {
user: SystemUserId,
source: std::io::Error,
},
/// Modifying a user failed
#[error("Modifying the user {user} failed:\n{source}")]
UserMod {
user: SystemUserId,
source: std::io::Error,
},
/// A system user name can not be derived from a configuration user name
#[error("Getting a system user for the username {user} failed:\n{source}")]
UserNameConversion {
user: SystemUserId,
source: nix::Error,
},
/// Writing authorized_keys file for user failed
#[error("Writing authorized_keys file for {user} failed:\n{source}")]
WriteAuthorizedKeys {
user: SystemUserId,
source: std::io::Error,
},
/// Writing sshd_config drop-in file for user failed
#[error("Writing sshd_config drop-in for {user} failed:\n{source}")]
WriteSshdConfig {
user: SystemUserId,
source: std::io::Error,
},
/// Writing tmpfiles.d integration for user failed
#[error("Writing tmpfiles.d integration for {user} failed:\n{source}")]
WriteTmpfilesD {
user: SystemUserId,
source: std::io::Error,
},
}
/// The configuration file path for the application.
///
/// If the path exists and is a file, one of the following configuration file locations is used:
/// - [`ETC_OVERRIDE_CONFIG_FILE`]
/// - [`RUN_OVERRIDE_CONFIG_FILE`]
/// - [`USR_LOCAL_OVERRIDE_CONFIG_FILE`]
///
/// If none of the above is found, [`DEFAULT_CONFIG_FILE`] is used (even if it doesn't exist!).
#[derive(Clone, Debug)]
pub struct ConfigPath(PathBuf);
impl ConfigPath {
pub fn new(path: PathBuf) -> Self {
Self(path)
}
}
impl AsRef<Path> for ConfigPath {
fn as_ref(&self) -> &Path {
self.0.as_path()
}
}
impl Default for ConfigPath {
/// Returns the default [`ConfigPath`].
///
/// If the path exists and is a file, one of the following configuration file locations is used:
/// - [`ETC_OVERRIDE_CONFIG_FILE`]
/// - [`RUN_OVERRIDE_CONFIG_FILE`]
/// - [`USR_LOCAL_OVERRIDE_CONFIG_FILE`]
///
/// If none of the above is found, [`DEFAULT_CONFIG_FILE`] is used (even if it doesn't exist!).
fn default() -> Self {
for config_file in [
ETC_OVERRIDE_CONFIG_FILE,
RUN_OVERRIDE_CONFIG_FILE,
USR_LOCAL_OVERRIDE_CONFIG_FILE,
] {
let config = PathBuf::from(config_file);
if config.is_file() {
return Self(config);
}
}
Self(PathBuf::from(DEFAULT_CONFIG_FILE))
}
}
impl From<PathBuf> for ConfigPath {
fn from(value: PathBuf) -> Self {
Self(value)
}
}
impl FromStr for ConfigPath {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self::new(PathBuf::from(s)))
}
}
/// A command enforced for a user connecting over SSH.
///
/// Tracks specific executables that are set using [ForceCommand] in an [sshd_config] drop-in
/// configuration.
///
/// [sshd_config]: https://man.archlinux.org/man/sshd_config.5
/// [ForceCommand]: https://man.archlinux.org/man/sshd_config.5#ForceCommand
#[derive(Debug, strum::AsRefStr, strum::Display, strum::EnumString, strum::VariantNames)]
pub enum SshForceCommand {
/// Enforce calling signstar-download-backup
#[strum(serialize = "signstar-download-backup")]
DownloadBackup,
/// Enforce calling signstar-download-key-certificate
#[strum(serialize = "signstar-download-key-certificate")]
DownloadKeyCertificate,
/// Enforce calling signstar-download-metrics
#[strum(serialize = "signstar-download-metrics")]
DownloadMetrics,
/// Enforce calling signstar-download-secret-share
#[strum(serialize = "signstar-download-secret-share")]
DownloadSecretShare,
/// Enforce calling signstar-download-signature
#[strum(serialize = "signstar-download-signature")]
DownloadSignature,
/// Enforce calling signstar-download-wireguard
#[strum(serialize = "signstar-download-wireguard")]
DownloadWireGuard,
/// Enforce calling signstar-upload-backup
#[strum(serialize = "signstar-upload-backup")]
UploadBackup,
/// Enforce calling signstar-upload-secret-share
#[strum(serialize = "signstar-upload-secret-share")]
UploadSecretShare,
/// Enforce calling signstar-upload-update
#[strum(serialize = "signstar-upload-update")]
UploadUpdate,
}
impl TryFrom<&UserMapping> for SshForceCommand {
type Error = Error;
fn try_from(value: &UserMapping) -> Result<Self, Self::Error> {
match value {
UserMapping::SystemNetHsmBackup {
nethsm_user: _,
ssh_authorized_key: _,
system_user: _,
} => Ok(Self::DownloadBackup),
UserMapping::SystemNetHsmMetrics {
nethsm_users: _,
ssh_authorized_key: _,
system_user: _,
} => Ok(Self::DownloadMetrics),
UserMapping::SystemNetHsmOperatorSigning {
nethsm_user: _,
nethsm_key_setup: _,
ssh_authorized_key: _,
system_user: _,
tag: _,
} => Ok(Self::DownloadSignature),
UserMapping::SystemOnlyShareDownload {
system_user: _,
ssh_authorized_keys: _,
} => Ok(SshForceCommand::DownloadSecretShare),
UserMapping::SystemOnlyShareUpload {
system_user: _,
ssh_authorized_keys: _,
} => Ok(SshForceCommand::UploadSecretShare),
UserMapping::SystemOnlyWireGuardDownload {
system_user: _,
ssh_authorized_keys: _,
} => Ok(SshForceCommand::DownloadWireGuard),
UserMapping::NetHsmOnlyAdmin(_)
| UserMapping::HermeticSystemNetHsmMetrics {
nethsm_users: _,
system_user: _,
} => Err(Error::NoForceCommandForMapping {
nethsm_users: value
.get_nethsm_users()
.iter()
.map(|user| user.to_string())
.collect(),
system_user: if let Some(system_user_id) = value.get_system_user() {
system_user_id.to_string()
} else {
"".to_string()
},
}),
}
}
}
/// Checks whether the current process is run by root.
///
/// Gets the effective user ID of the current process and checks whether it is `0`.
///
/// # Errors
///
/// Returns an error if
/// - conversion of PID to usize `fails`
/// - the root user ID can not be converted from `"0"`
/// - no user ID can be retrieved from the current process
/// - the process is not run by root
pub fn ensure_root() -> Result<(), Error> {
let pid: usize = id()
.try_into()
.map_err(|_| Error::FailedU32ToUsizeConversion)?;
let system = System::new_all();
let Some(process) = system.process(Pid::from(pid)) else {
return Err(Error::NoProcess);
};
let Some(uid) = process.effective_user_id() else {
return Err(Error::NoUidForProcess(pid));
};
let root_uid_str = "0";
let root_uid = sysinfo::Uid::from_str(root_uid_str)
.map_err(|_| Error::SysUidFromStr(root_uid_str.to_string()))?;
if uid.ne(&root_uid) {
return Err(Error::NotRoot);
}
Ok(())
}
/// Creates system users and their integration.
///
/// Works on the [`UserMapping`]s of the provided `config` and creates system users for all
/// mappings, that define system users, if they don't exist on the system yet.
/// System users are created unlocked, without passphrase, with their homes located in
/// [`HOME_BASE_DIR`].
/// The home directories of users are not created upon user creation, but instead a [tmpfiles.d]
/// configuration is added for them to automate their creation upon system boot.
///
/// Additionally, if an [`SshForceCommand`] can be derived from the particular [`UserMapping`] and
/// one or more SSH [authorized_keys] are defined for it, a dedicated SSH integration is created for
/// the system user.
/// This entails the creation of a dedicated [authorized_keys] file as well as an [sshd_config]
/// drop-in in a system-wide location.
/// Depending on [`UserMapping`], a specific [ForceCommand] is set for the system user, reflecting
/// its role in the system.
///
/// # Errors
///
/// Returns an error if
/// - a system user name ([`SystemUserId`]) in the configuration can not be transformed into a valid
/// system user name [`User`]
/// - a new user can not be created
/// - a newly created user can not be modified
/// - the tmpfiles.d integration for a newly created user can not be created
/// - the sshd_config drop-in file for a newly created user can not be created
///
/// [tmpfiles.d]: https://man.archlinux.org/man/tmpfiles.d.5
/// [authorized_keys]: https://man.archlinux.org/man/sshd.8#AUTHORIZED_KEYS_FILE_FORMAT
/// [sshd_config]: https://man.archlinux.org/man/sshd_config.5
/// [ForceCommand]: https://man.archlinux.org/man/sshd_config.5#ForceCommand
pub fn create_system_users(config: &HermeticParallelConfig) -> Result<(), Error> {
for mapping in config.iter_user_mappings() {
// if there is no system user, there is nothing to do
let Some(user) = mapping.get_system_user() else {
continue;
};
// if the system user exists already, there is nothing to do
if User::from_name(user.as_ref())
.map_err(|source| Error::UserNameConversion {
user: user.clone(),
source,
})?
.is_some()
{
eprintln!("Skipping existing user \"{user}\"...");
continue;
}
// add user, but do not create its home
print!("Creating user \"{user}\"...");
let user_add = Command::new("useradd")
.args([
"--base-dir",
HOME_BASE_DIR,
"--user-group",
"--shell",
"/usr/bin/bash",
user.as_ref(),
])
.output()
.map_err(|error| Error::UserAdd {
user: user.clone(),
source: error,
})?;
if !user_add.status.success() {
return Err(Error::CommandNonZero {
exit_status: user_add.status,
stderr: String::from_utf8_lossy(&user_add.stderr).into_owned(),
});
} else {
println!(" Done.");
}
// modify user to unlock it
print!("Unlocking user \"{user}\"...");
let user_mod = Command::new("usermod")
.args(["--unlock", user.as_ref()])
.output()
.map_err(|source| Error::UserMod {
user: user.clone(),
source,
})?;
if !user_mod.status.success() {
return Err(Error::CommandNonZero {
exit_status: user_mod.status,
stderr: String::from_utf8_lossy(&user_mod.stderr).into_owned(),
});
} else {
println!(" Done.");
}
// add tmpfiles.d integration for the user to create its home directory
print!("Adding tmpfiles.d integration for user \"{user}\"...");
{
let mut buffer = File::create(format!("/usr/lib/tmpfiles.d/signstar-user-{user}.conf"))
.map_err(|source| Error::WriteTmpfilesD {
user: user.clone(),
source,
})?;
buffer
.write_all(format!("d {HOME_BASE_DIR}/{user} 700 {user} {user}\n").as_bytes())
.map_err(|source| Error::WriteTmpfilesD {
user: user.clone(),
source,
})?;
}
println!(" Done.");
if let Ok(force_command) = SshForceCommand::try_from(mapping) {
let authorized_keys = mapping.get_ssh_authorized_keys();
if !authorized_keys.is_empty() {
// add SSH authorized keys file user in system-wide location
print!("Adding SSH authorized_keys file for user \"{user}\"...");
{
let filename = format!(
"{SSH_AUTHORIZED_KEY_BASE_DIR}/signstar-user-{user}.authorized_keys"
);
let mut buffer =
File::create(filename).map_err(|source| Error::WriteAuthorizedKeys {
user: user.clone(),
source,
})?;
buffer
.write_all(
(authorized_keys
.iter()
.map(|authorized_key| authorized_key.as_ref())
.collect::<Vec<&str>>()
.join("\n")
+ "\n")
.as_bytes(),
)
.map_err(|source| Error::WriteAuthorizedKeys {
user: user.clone(),
source,
})?;
}
println!(" Done.");
// add sshd_config drop-in configuration for user
print!("Adding sshd_config drop-in configuration for user \"{user}\"...");
{
let mut buffer = File::create(format!(
"{SSHD_DROPIN_CONFIG_DIR}/10-signstar-user-{user}.conf"
))
.map_err(|source| Error::WriteSshdConfig {
user: user.clone(),
source,
})?;
buffer
.write_all(
format!(
r#"Match user {user}
AuthorizedKeysFile /etc/ssh/signstar-user-{user}.authorized_keys
ForceCommand /usr/bin/{force_command}
"#
)
.as_bytes(),
)
.map_err(|source| Error::WriteSshdConfig {
user: user.clone(),
source,
})?;
}
println!(" Done.");
}
};
}
Ok(())
}