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
|
use crate::config::NodeConfig;
use crate::proto::{BACKUP_DIR, SNAPSHOT_DIR};
use crate::LocalNodeError;
use std::fs;
use std::io::BufRead;
use std::net::SocketAddr;
use std::path::Path;
use std::process::Command;
use argon2::Argon2;
use hmac::{Hmac, Mac};
use rand::Rng;
use sha2::Sha256;
use sys_mount::{Mount, UnmountFlags};
pub const MOUNTPOINTC: &str = "/mnt/hbak";
pub const MOUNTPOINTS: &str = "/mnt/hbakd";
/// Initializes the configuration file and local btrfs subvolumes.
pub fn init(
config_only: bool,
device: String,
bind_addr: Option<SocketAddr>,
node_name: String,
passphrase: String,
) -> Result<(), LocalNodeError> {
if Path::new(NodeConfig::PATH).exists() {
return Err(LocalNodeError::ConfigExists);
}
let node_config = NodeConfig {
device,
bind_addr,
node_name,
subvols: Vec::default(),
passphrase,
remotes: Vec::default(),
auth: Vec::default(),
};
node_config.save()?;
if !config_only {
init_btrfs(&node_config.device)?;
}
Ok(())
}
fn init_btrfs(device: &str) -> Result<(), LocalNodeError> {
fs::create_dir_all(MOUNTPOINTC)?;
fs::create_dir_all(MOUNTPOINTS)?;
let _btrfs = Mount::builder().data("compress=zstd").mount_autodrop(
device,
MOUNTPOINTC,
UnmountFlags::DETACH,
)?;
if !Command::new("btrfs")
.arg("subvolume")
.arg("create")
.arg(SNAPSHOT_DIR)
.spawn()?
.wait()?
.success()
{
return Err(LocalNodeError::BtrfsCmd);
}
if !Command::new("btrfs")
.arg("subvolume")
.arg("create")
.arg(BACKUP_DIR)
.spawn()?
.wait()?
.success()
{
return Err(LocalNodeError::BtrfsCmd);
}
Ok(())
}
/// Deinitializes the configuration file, optionally deleting the btrfs subvolumes.
pub fn deinit(remove_backups: bool) -> Result<(), LocalNodeError> {
if !Path::new(NodeConfig::PATH).exists() {
return Err(LocalNodeError::ConfigUninit);
}
if remove_backups {
deinit_btrfs()?;
}
fs::remove_file(NodeConfig::PATH)?;
Ok(())
}
fn deinit_btrfs() -> Result<(), LocalNodeError> {
fs::create_dir_all(MOUNTPOINTC)?;
fs::create_dir_all(MOUNTPOINTS)?;
let node_config = NodeConfig::load()?;
let _btrfs = Mount::builder().data("compress=zstd").mount_autodrop(
node_config.device,
MOUNTPOINTC,
UnmountFlags::DETACH,
)?;
if !Command::new("btrfs")
.arg("subvolume")
.arg("delete")
.arg(BACKUP_DIR)
.spawn()?
.wait()?
.success()
{
return Err(LocalNodeError::BtrfsCmd);
}
let output = Command::new("btrfs")
.arg("subvolume")
.arg("list")
.arg("-o")
.arg(SNAPSHOT_DIR)
.output()?;
if !output.status.success() {
return Err(LocalNodeError::BtrfsCmd);
}
let subvols = output.stdout.lines().map(|line| match line {
Ok(line) => Ok(Path::new(MOUNTPOINTC).join(
line.split_whitespace()
.next_back()
.expect("String splitting yields at least one item"),
)),
Err(e) => Err(e),
});
for subvol in subvols {
if !Command::new("btrfs")
.arg("subvolume")
.arg("delete")
.arg(subvol?)
.spawn()?
.wait()?
.success()
{
return Err(LocalNodeError::BtrfsCmd);
}
}
if !Command::new("btrfs")
.arg("subvolume")
.arg("delete")
.arg(SNAPSHOT_DIR)
.spawn()?
.wait()?
.success()
{
return Err(LocalNodeError::BtrfsCmd);
}
Ok(())
}
/// Provides a `Vec<u8>` of `n` random bytes. Uses the thread-local generator
/// of the `rand` crate.
pub fn random_bytes(n: usize) -> Vec<u8> {
rand::thread_rng()
.sample_iter(&rand::distributions::Standard)
.take(n)
.collect()
}
/// Performs an HMAC-SHA256 hash computation.
pub fn hash_hmac(secret: &[u8], data: &[u8]) -> Vec<u8> {
let mut mac: Hmac<Sha256> =
Hmac::new_from_slice(secret).expect("HMAC can take key of any size");
mac.update(data);
let hmac = mac.finalize();
hmac.into_bytes().to_vec()
}
/// Performs an Argon2id hash computation.
pub fn hash_argon2id<P: AsRef<[u8]>>(
okm: &mut [u8],
salt: &[u8],
passphrase: P,
) -> Result<(), LocalNodeError> {
Argon2::new(
argon2::Algorithm::Argon2id,
argon2::Version::default(),
argon2::Params::new(524288, 32, 128, Some(32))?,
)
.hash_password_into(passphrase.as_ref(), salt, okm)?;
Ok(())
}
/// Converts the provided passphrase into a key
/// suitable for node authentication or encryption using a random verifier.
///
/// This function wraps the [`derive_key`] function.
///
/// Returns the verifier and the HMAC hash in this order.
pub fn hash_passphrase<P: AsRef<[u8]>>(
passphrase: P,
) -> Result<(Vec<u8>, Vec<u8>), LocalNodeError> {
let verifier = random_bytes(32);
let key = derive_key(&verifier, passphrase)?;
Ok((verifier, key))
}
/// Converts the provided verifier and passphrase into a key
/// for node authentication or encryption.
pub fn derive_key<P: AsRef<[u8]>>(
verifier: &[u8],
passphrase: P,
) -> Result<Vec<u8>, LocalNodeError> {
let mut key_array = [0; 32];
hash_argon2id(&mut key_array, verifier, passphrase)?;
let key = hash_hmac(&key_array, verifier);
Ok(key)
}
|