-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathutil.rs
More file actions
297 lines (268 loc) · 10.5 KB
/
util.rs
File metadata and controls
297 lines (268 loc) · 10.5 KB
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
use rust_i18n::t;
use serde_json::{Map, Value};
use std::{path::PathBuf, process::Command};
use tracing::{debug, warn, Level};
use tracing_subscriber::{EnvFilter, Layer, prelude::__tracing_subscriber_SubscriberExt};
use crate::args::{TraceFormat, TraceLevel};
use crate::canonical_properties::{CanonicalProperty, CanonicalProperties};
use crate::error::SshdConfigError;
use crate::inputs::{CommandInfo, Metadata, SshdCommandArgs};
use crate::metadata::{SSHD_CONFIG_DEFAULT_PATH_UNIX, SSHD_CONFIG_DEFAULT_PATH_WINDOWS};
use crate::parser::parse_text_to_map;
/// Enable tracing.
///
/// # Arguments
///
/// * `trace_level` - The level of information to output
/// * `trace_format` - The format of the output
///
/// # Errors
///
/// This function will return an error if it fails to initialize tracing.
pub fn enable_tracing(trace_level: Option<&TraceLevel>, trace_format: &TraceFormat) {
let trace_level = match trace_level {
Some(trace_level) => trace_level,
None => {
if let Ok(trace_level) = std::env::var("DSC_TRACE_LEVEL") {
&match trace_level.to_lowercase().as_str() {
"error" => TraceLevel::Error,
"warn" => TraceLevel::Warn,
"info" => TraceLevel::Info,
"debug" => TraceLevel::Debug,
"trace" => TraceLevel::Trace,
_ => {
eprintln!("{}: {trace_level}", t!("main.invalidTraceLevel"));
TraceLevel::Info
}
}
} else {
&TraceLevel::Info
}
}
};
let tracing_level = match trace_level {
TraceLevel::Error => Level::ERROR,
TraceLevel::Warn => Level::WARN,
TraceLevel::Info => Level::INFO,
TraceLevel::Debug => Level::DEBUG,
TraceLevel::Trace => Level::TRACE,
};
let filter = EnvFilter::try_from_default_env()
.or_else(|_| EnvFilter::try_new("warn"))
.unwrap_or_default()
.add_directive(tracing_level.into());
let layer = tracing_subscriber::fmt::Layer::default().with_writer(std::io::stderr);
let fmt = match trace_format {
TraceFormat::Default => {
layer
.with_ansi(true)
.with_level(true)
.with_line_number(true)
.boxed()
},
TraceFormat::Plaintext => {
layer
.with_ansi(false)
.with_level(true)
.with_line_number(false)
.boxed()
},
TraceFormat::Json => {
layer
.with_ansi(false)
.with_level(true)
.with_line_number(true)
.json()
.boxed()
}
};
let subscriber = tracing_subscriber::Registry::default().with(fmt).with(filter);
if tracing::subscriber::set_global_default(subscriber).is_err() {
eprintln!("{}", t!("util.tracingInitError"));
}
}
/// Get the `sshd_config` path
/// Uses the input value, if provided.
/// If input value not provided, get default path for the OS.
/// On Windows, uses the `ProgramData` environment variable and standard path.
/// On Unix-like systems, uses the standard path.
pub fn get_default_sshd_config_path(input: Option<PathBuf>) -> Result<PathBuf, SshdConfigError> {
if let Some(path) = input {
Ok(path)
} else if cfg!(windows) {
let program_data = std::env::var("ProgramData")?;
Ok(PathBuf::from(format!("{program_data}{SSHD_CONFIG_DEFAULT_PATH_WINDOWS}")))
} else {
Ok(PathBuf::from(SSHD_CONFIG_DEFAULT_PATH_UNIX))
}
}
fn get_sshd_config_default_source_candidates() -> Vec<PathBuf> {
let mut candidates: Vec<PathBuf> = Vec::new();
if cfg!(windows) && let Ok(system_drive) = std::env::var("SystemDrive") {
candidates.push(PathBuf::from(format!("{system_drive}\\Windows\\System32\\OpenSSH\\sshd_config_default")));
}
candidates
}
/// Ensure the target `sshd_config` exists by seeding it from a platform default source.
///
/// # Errors
///
/// This function returns an error if the target cannot be created or no source default config is available.
pub fn ensure_sshd_config_exists(input: Option<PathBuf>) -> Result<PathBuf, SshdConfigError> {
let target_path = get_default_sshd_config_path(input)?;
if target_path.exists() {
return Ok(target_path);
}
if !cfg!(windows) {
return Err(SshdConfigError::FileNotFound(
t!("util.sshdConfigNotFoundNonWindows").to_string()
));
}
let candidates = get_sshd_config_default_source_candidates();
let source_path = candidates
.iter()
.find(|candidate| candidate.is_file())
.cloned()
.ok_or_else(|| {
let paths = candidates
.iter()
.map(|path| path.display().to_string())
.collect::<Vec<String>>()
.join(", ");
SshdConfigError::InvalidInput(t!("util.sshdConfigDefaultNotFound", paths = paths).to_string())
})?;
if let Some(parent) = target_path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::copy(&source_path, &target_path)?;
debug!("{}", t!("util.seededConfigFromDefault", source = source_path.display(), target = target_path.display()));
Ok(target_path)
}
/// Invoke sshd -T.
///
/// # Errors
///
/// This function will return an error if sshd -T fails to validate `sshd_config`.
pub fn invoke_sshd_config_validation(args: Option<SshdCommandArgs>) -> Result<String, SshdConfigError> {
let mut command = Command::new("sshd");
command.arg("-T");
if let Some(args) = args {
if let Some(filepath) = args.filepath {
if !filepath.exists() {
return Err(SshdConfigError::FileNotFound(filepath.display().to_string()));
}
command.arg("-f").arg(&filepath);
}
if let Some(additional_args) = args.additional_args {
command.args(additional_args);
}
}
let output = command.output()
.map_err(|e| SshdConfigError::CommandError(e.to_string()))?;
if output.status.success() {
let stdout = String::from_utf8(output.stdout)
.map_err(|e| SshdConfigError::CommandError(e.to_string()))?;
Ok(stdout)
} else {
let stderr = String::from_utf8(output.stderr)
.map_err(|e| SshdConfigError::CommandError(e.to_string()))?;
if stderr.contains("sshd: no hostkeys available") || stderr.contains("Permission denied") {
return Err(SshdConfigError::CommandError(
t!("util.sshdElevation").to_string()
));
}
Err(SshdConfigError::CommandError(stderr))
}
}
/// Extract SSH server defaults by running sshd -T with an empty configuration file.
///
/// # Errors
///
/// This function will return an error if it fails to extract the defaults from sshd.
pub fn extract_sshd_defaults() -> Result<Map<String, Value>, SshdConfigError> {
let temp_file = tempfile::Builder::new()
.prefix("sshd_config_empty_")
.suffix(".tmp")
.tempfile()?;
// on Windows, sshd cannot read from the file if it is still open
let temp_path = temp_file.path().to_path_buf();
// do not automatically delete the file when it goes out of scope
let (file, path) = temp_file.keep()?;
// close the file handle to allow sshd to read it
drop(file);
debug!("{}", t!("util.tempFileCreated", path = temp_path.display()));
let args = Some(
SshdCommandArgs {
filepath: Some(temp_path),
additional_args: None,
}
);
// Clean up the temporary file regardless of success or failure
let output = invoke_sshd_config_validation(args);
if let Err(e) = std::fs::remove_file(&path) {
debug!("{}", t!("util.cleanupFailed", path = path.display(), error = e));
}
let result = output?;
let sshd_config: Map<String, Value> = parse_text_to_map(&result)?;
Ok(sshd_config)
}
/// Extract _metadata field from the input string, if it can be parsed as JSON.
///
/// # Errors
///
/// This function will return an error if it fails to parse the input string and if the _metadata field exists, extract it.
pub fn build_command_info(input: Option<&String>, is_get: bool) -> Result<CommandInfo, SshdConfigError> {
let mut include_defaults = is_get;
let mut metadata: Metadata = Metadata::new();
let mut purge = false;
let mut sshd_args: Option<SshdCommandArgs> = None;
let mut sshd_config: Map<String, Value> = Map::new();
if let Some(inputs) = input {
sshd_config = serde_json::from_str(inputs.as_str())?;
purge = CanonicalProperties::extract_bool(&mut sshd_config, CanonicalProperty::Purge, false)?;
include_defaults = CanonicalProperties::extract_bool(&mut sshd_config, CanonicalProperty::IncludeDefaults, is_get)?;
metadata = if let Some(value) = sshd_config.remove(CanonicalProperty::Metadata.as_str()) {
serde_json::from_value(value)?
} else {
Metadata::new()
};
sshd_args = metadata.filepath.clone().map(|filepath| {
SshdCommandArgs {
filepath: Some(filepath),
additional_args: None,
}
});
if is_get && !sshd_config.is_empty() {
warn!("{}", t!("util.getIgnoresInputFilters"));
sshd_config.clear();
}
}
Ok(CommandInfo::new(include_defaults, sshd_config, metadata, purge, sshd_args))
}
/// Reads `sshd_config` file.
///
/// # Arguments
///
/// * `input` - Optional `PathBuf` with `sshd_config` filepath.
///
/// # Errors
///
/// This function will return an error if the file cannot be found or read.
pub fn read_sshd_config(input: Option<PathBuf>) -> Result<String, SshdConfigError> {
let filepath = get_default_sshd_config_path(input)?;
if filepath.exists() {
let mut sshd_config_content = String::new();
if let Ok(mut file) = std::fs::OpenOptions::new().read(true).open(&filepath) {
use std::io::Read;
file.read_to_string(&mut sshd_config_content)
.map_err(|e| SshdConfigError::CommandError(e.to_string()))?;
} else {
return Err(SshdConfigError::CommandError(t!("util.sshdConfigReadFailed", path = filepath.display()).to_string()));
}
Ok(sshd_config_content)
} else {
Err(SshdConfigError::FileNotFound(filepath.display().to_string()))
}
}