Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
295 lines (275 loc) · 9.67 KB
/
Copy pathlib.rs
File metadata and controls
295 lines (275 loc) · 9.67 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
#[macro_use]
extern crate log;
pub mod cli;
pub mod error;
pub mod cmd {
mod check;
mod decrypt;
mod edit;
mod encrypt;
mod env;
mod keygen;
mod pubkey;
pub use check::check;
pub use decrypt::decrypt;
pub use edit::edit;
pub use encrypt::encrypt;
pub use env::env;
pub use keygen::keygen;
pub use pubkey::pubkey;
}
use std::fs::{File, OpenOptions};
use std::io::{stdin, stdout, BufRead, BufReader, Read, Write};
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use std::path::Path;
use std::path::PathBuf;
use std::str::FromStr;
use age::x25519;
use base64::prelude::*;
use serde_yaml as sy;
use strum::{Display, EnumIs, EnumIter, EnumString};
use substring::Substring;
use crate::error::{IOResultExt, Result, YageError};
pub fn stdout_or_file(path: &Path) -> Result<Box<dyn Write>> {
Ok(if path == Path::new("-") {
Box::new(stdout())
} else {
Box::new(File::create(path).path_ctx(path)?)
})
}
pub fn stdout_or_private_file(path: &Path) -> Result<Box<dyn Write>> {
Ok(if path == Path::new("-") {
Box::new(stdout())
} else {
Box::new(create_private_file(path)?)
})
}
pub fn create_private_file(path: &Path) -> Result<File> {
let mut file_opts = OpenOptions::new();
file_opts.write(true).create_new(true);
#[cfg(unix)]
file_opts.mode(0o600);
file_opts.open(path).path_ctx(path)
}
pub fn stdin_or_file(path: &Path) -> Result<BufReader<Box<dyn Read>>> {
Ok(if path == Path::new("-") {
BufReader::new(Box::new(stdin()))
} else {
BufReader::new(Box::new(File::open(path).path_ctx(path)?))
})
}
pub fn stdin_or_private_file(path: &Path) -> Result<BufReader<Box<dyn Read>>> {
Ok(if path == Path::new("-") {
BufReader::new(Box::new(stdin()))
} else {
let br: BufReader<Box<dyn Read>> =
BufReader::new(Box::new(File::open(path).path_ctx(path)?));
if let Err(e) = fs_mistrust::Mistrust::new()
.verifier()
.require_file()
.check(path)
{
warn!("file {path:?} is not private: {e}");
}
br
})
}
pub fn is_yage_encoded(s: &str) -> bool {
s.starts_with("yage[") && s.ends_with(']')
}
pub fn decrypt_yaml(value: &sy::Value, identities: &[x25519::Identity]) -> Result<sy::Value> {
match value {
sy::Value::Mapping(mapping) => {
let mut output = sy::Mapping::new();
for (key, value) in mapping {
let key = key.clone();
let value = decrypt_yaml(value, identities)?;
output.insert(key, value);
}
Ok(sy::Value::Mapping(output))
}
sy::Value::Sequence(sequence) => {
let mut output = Vec::new();
for value in sequence {
let value = decrypt_yaml(value, identities)?;
output.push(value);
}
Ok(sy::Value::Sequence(output))
}
sy::Value::String(encrypted) => {
let decrypted = decrypt_value(encrypted, identities)?;
Ok(decrypted)
}
_ => Ok(value.clone()),
}
}
pub fn decrypt_value(s: &str, identities: &[x25519::Identity]) -> Result<sy::Value> {
if is_yage_encoded(s) {
// remove the yage[…] prefix and suffix
let encoded = s.substring(5, s.len() - 1);
let encrypted = BASE64_STANDARD.decode(encoded)?;
let decryptor = match age::Decryptor::new(&encrypted[..])? {
age::Decryptor::Recipients(d) => Ok(d),
_ => Err(YageError::PassphraseUnsupported),
}?;
let mut decrypted = vec![];
let mut reader = decryptor.decrypt(identities.iter().map(|i| i as &dyn age::Identity))?;
reader.read_to_end(&mut decrypted)?;
let value: sy::Value = sy::from_slice(&decrypted)?;
Ok(value)
} else {
Ok(sy::Value::String(s.to_owned()))
}
}
pub fn load_identities(keys: &[String], key_files: &[PathBuf]) -> Result<Vec<x25519::Identity>> {
let mut identities: Vec<x25519::Identity> = Vec::new();
for key in keys.iter() {
debug!("loading key: {key}");
let key = x25519::Identity::from_str(key)
.map_err(|e| YageError::KeyParse { message: e.into() })?;
identities.push(key);
}
for key_file in key_files.iter() {
debug!("loading key file: {key_file:?}");
let input = stdin_or_private_file(key_file)?;
let keys = age::IdentityFile::from_buffer(input).path_ctx(key_file)?;
for key in keys.into_identities() {
let age::IdentityFileEntry::Native(key) = key;
identities.push(key);
}
}
Ok(identities)
}
pub fn encrypt_yaml(value: &sy::Value, recipients: &[x25519::Recipient]) -> Result<sy::Value> {
match value {
sy::Value::Mapping(mapping) => {
let mut output = sy::Mapping::new();
for (key, value) in mapping {
let key = key.clone();
let value = encrypt_yaml(value, recipients)?;
output.insert(key, value);
}
Ok(sy::Value::Mapping(output))
}
sy::Value::Sequence(sequence) => {
let mut output = Vec::new();
for value in sequence {
let value = encrypt_yaml(value, recipients)?;
output.push(value);
}
Ok(sy::Value::Sequence(output))
}
sy::Value::String(s) => {
let output = if is_yage_encoded(s) {
// keep the already encrypted value
s.to_owned()
} else {
encrypt_value(value, recipients)?
};
Ok(sy::Value::String(output))
}
sy::Value::Number(_) => {
let output = encrypt_value(value, recipients)?;
Ok(sy::Value::String(output))
}
_ => Ok(value.clone()),
}
}
pub fn encrypt_value(value: &sy::Value, recipients: &[x25519::Recipient]) -> Result<String> {
type Recipients = Vec<Box<dyn age::Recipient + Send + 'static>>;
let data = sy::to_string(value)?;
let recipients = recipients
.iter()
.map(|r| Box::new(r.clone()) as Box<dyn age::Recipient + Send + 'static>)
.collect::<Recipients>();
let mut encrypted = vec![];
let encryptor = age::Encryptor::with_recipients(recipients).ok_or(YageError::NoRecipients)?;
// let mut armored = ArmoredWriter::wrap_output(&mut encrypted, Format::AsciiArmor)?;
let mut writer = encryptor.wrap_output(&mut encrypted)?;
writer.write_all(data.as_bytes())?;
writer.finish()?;
let encoded = BASE64_STANDARD.encode(&encrypted);
Ok(format!("yage[{encoded}]"))
}
pub fn load_recipients(
recipients: &[String],
recipients_paths: &[PathBuf],
) -> Result<Vec<x25519::Recipient>> {
let mut res: Vec<x25519::Recipient> = Vec::new();
// read the recipient from the command line
for recipient in recipients.iter() {
debug!("loading recipient: {recipient}");
let recipient =
x25519::Recipient::from_str(recipient).map_err(|e| YageError::RecipientParse {
recipient: recipient.to_owned(),
message: e.into(),
})?;
res.push(recipient);
}
// read the recipient from the files
for path in recipients_paths.iter() {
debug!("loading recipient file: {path:?}");
let input = stdin_or_file(path)?;
for recipient in input.lines() {
let recipient = recipient.path_ctx(path)?;
let recipient =
x25519::Recipient::from_str(&recipient).map_err(|e| YageError::RecipientParse {
recipient: recipient.to_owned(),
message: e.into(),
})?;
res.push(recipient);
}
}
Ok(res)
}
#[derive(Debug, Clone, Copy, PartialEq, Display, EnumString, EnumIs, EnumIter)]
pub enum EncryptionStatus {
Encrypted,
NotEncrypted,
Mixed,
NoValue,
}
pub fn check_encrypted(value: &sy::Value) -> EncryptionStatus {
match value {
sy::Value::Mapping(mapping) => check_encrypted_iter(mapping.iter().map(|(_, v)| v)),
sy::Value::Sequence(sequence) => check_encrypted_iter(sequence.iter()),
sy::Value::String(s) => {
if is_yage_encoded(s) {
EncryptionStatus::Encrypted
} else {
EncryptionStatus::NotEncrypted
}
}
sy::Value::Null => EncryptionStatus::NoValue,
_ => EncryptionStatus::NotEncrypted,
}
}
fn check_encrypted_iter<'a>(iter: impl Iterator<Item = &'a sy::Value>) -> EncryptionStatus {
let mut status = EncryptionStatus::NoValue;
for value in iter {
match check_encrypted(value) {
EncryptionStatus::Encrypted => {
status = match status {
EncryptionStatus::Encrypted => EncryptionStatus::Encrypted,
EncryptionStatus::NotEncrypted => EncryptionStatus::Mixed,
EncryptionStatus::Mixed => EncryptionStatus::Mixed,
EncryptionStatus::NoValue => EncryptionStatus::Encrypted,
}
}
EncryptionStatus::NotEncrypted => {
status = match status {
EncryptionStatus::Encrypted => EncryptionStatus::Mixed,
EncryptionStatus::NotEncrypted => EncryptionStatus::NotEncrypted,
EncryptionStatus::Mixed => EncryptionStatus::Mixed,
EncryptionStatus::NoValue => EncryptionStatus::NotEncrypted,
}
}
EncryptionStatus::Mixed => {
status = EncryptionStatus::Mixed;
}
EncryptionStatus::NoValue => (),
}
}
status
}